package com.chris.cc.oauth2.service.impl;

import com.chris.cc.common.user.Permission;
import com.chris.cc.common.user.Role;
import com.chris.cc.common.user.User;
import com.chris.cc.common.web.R;
import com.chris.cc.oauth2.config.MD5PasswordEncoder;
import com.chris.cc.oauth2.service.CustomUserDetailsService;
import com.chris.cc.oauth2.service.http.UserClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Copyright (c) 2018-2025, chris All rights reserved.
 * <p>
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * <p>
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: haoka (haokang207@126.com)
 * Date: 2018/8/10 18:06
 **/
@Service
@Slf4j
public class UserDetailsServiceImpl implements CustomUserDetailsService {
    @Value("${cc.username}")
    private String username;
    @Value("${cc.password}")
    private String password;
    @Autowired
    private UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("获取用户信息：" + username);
        if (this.username.equals(username)) {//接口权限，非普通用户验证
            return org.springframework.security.core.userdetails.User.builder().accountExpired(false)
                    .accountLocked(false)
                    .credentialsExpired(false)
                    .disabled(false)
                    .passwordEncoder(password -> new MD5PasswordEncoder().encode(password))
                    .password(password)
                    .username(username)
                    .roles("admin")
                    .authorities(new SimpleGrantedAuthority("admin"))
                    .build();
        }
        R<User> result = userClient.getUserByTel(username);
        User user = result.getData();
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        R<List<Role>> roleResult = userClient.getRolesByUserId(user.getUserId());
        if (roleResult.getData() == null) {
            return null;
        }
        List<String> roles = roleResult.getData().stream().map(Role::getCode).collect(Collectors.toList());
        String rolesStr = StringUtils.join(roles, ",");
        R<List<Permission>> permissionsR = userClient.getPermissionsByUserId(user.getUserId());
        SimpleGrantedAuthority[] authorities = permissionsR.getData().stream()
                .map(Permission::getCode)
                .map(SimpleGrantedAuthority::new)
                .toArray(SimpleGrantedAuthority[]::new);
        return org.springframework.security.core.userdetails.User.builder().accountExpired(false)
                .accountLocked(false)
                .credentialsExpired(false)
                .disabled(!user.getEnable())
                .password(user.getPassword())
                .passwordEncoder(p -> user.getPassword())
                .username(username)
                .roles(rolesStr)
                .authorities(authorities)
                .build();
    }

    @Override
    public List<String> loadPermissionsByUsername(Object username) {
        log.info("获取用户权限：" + username);
        if (this.username.equals(username)) {//接口权限，非普通用户验证
            return Collections.singletonList("*");
        }
        R<User> result = userClient.getUserByTel(username.toString());
        User user = result.getData();
        if (user == null) {
            return Collections.emptyList();
        }
        R<List<Permission>> permissionsR = userClient.getPermissionsByUserId(user.getUserId());
        if (permissionsR == null) {
            return Collections.emptyList();
        }
        List<Permission> permissions = permissionsR.getData();
        return permissions.stream().map(Permission::getCode).collect(Collectors.toList());
    }
}
